<?php

namespace app\admin\controller\device;

use app\common\model\School;
use app\common\controller\Backend;
use app\common\model\DeviceKey;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 激活码分配
 *
 * Class Device
 * @package app\admin\controller\device
 */
class Distribute extends Backend
{
    /**
     * @var \app\common\model\Device
     */
    protected $model = null;
    protected $searchFields = 'id,name';
    protected $noNeedRight = ['searchlist'];
    protected $schoolLimit = true;
    protected $schoolIds = [];
    protected $device = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Device');

        if ($this->auth->isSuperAdmin()) {
            $this->schoolIds = $this->auth->getChildrenSchoolIds(true);
        } else {
            $this->schoolIds = $this->auth->getChildrenSchoolIds();
        }

        $schoolList = collection(School::where('id', 'in', $this->schoolIds)->select())->toArray();

        $schoolTree = new Tree();
        $schoolTree->init($schoolList);
        $schooldata = [];

        if ($this->auth->isSuperAdmin()) {
            $school_result = $schoolTree->getTreeList($schoolTree->getTreeArray(0));
            foreach ($school_result as $k => $v) {
                $schooldata[$v['id']] = $v['name'];
            }

        } else {
            $school_childlist = $schoolTree->getTreeList($schoolTree->getTreeArray($this->auth->school_id));

            $school_result = [];
            foreach ($school_childlist as $k => $v) {
                $school_result[$v['id']] = $v['name'];
            }
            $schooldata = $school_result;
        }

        $this->view->assign('schoolData', $schooldata);

        $this->device = \app\common\model\Device::where('school_id', $this->auth->school_id)->find();

        $this->view->assign('device', $this->device);

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (!$this->device) {
                    $this->error(__('激活码数量不足'));
                }

                $count = $this->device->count - $this->device->used_count;
                if ($params['count'] > $count) {
                    $this->error(__('生成数量大于可用数量'));
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $params['app_id'] = $this->device->app_id;
                    $params['sdk_key'] = $this->device->sdk_key;
                    $params['expired_at'] = $this->device->expired_at;
                    $params['pid'] = $this->device->id;

                    \app\common\model\Device::where('id', $this->device->id)->setInc('used_count', $params['count']);

                    $params['used_count'] = $params['count'];
                    $result = $this->model->allowField(true)->save($params);

                    if ($result) {
                        $device_key = new \app\common\model\DeviceKey();

                        $insert_data = [];
                        for ($i = 0; $i < $params['count']; $i++) {
                            $insert_data[] = [
                                'device_id' => $this->model->id,
                                'key' => unique()
                            ];
                        }

                        $result = $device_key->saveAll($insert_data);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();
        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($row['id'] != $this->device->id) {
                    $count = $this->device->count - $this->device->used_count;
                    $key_count = $params['count'] - $row['count'];
                    if ($key_count > $count) {
                        $this->error(__('生成数量大于可用数量'));
                    }
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if ($row['id'] != $this->device->id) {
                        $params['app_id'] = $this->device->app_id;
                        $params['sdk_key'] = $this->device->sdk_key;
                        $params['expired_at'] = $this->device->expired_at;
                        $params['pid'] = $this->device->id;

                        \app\common\model\Device::where('id', $this->device->id)->setInc('used_count', $key_count);

                        $params['used_count'] = $params['count'];
                        $result = $this->model->allowField(true)->save($params);

                        $result = $row->allowField(true)->save($params);

                        if ($result) {
                            $device_key = new \app\common\model\DeviceKey();

                            $insert_data = [];
                            for ($i = 0; $i < $key_count; $i++) {
                                $insert_data[] = [
                                    'device_id' => $row['id'],
                                    'key' => unique()
                                ];
                            }

                            $result = $device_key->saveAll($insert_data);
                        }
                    } else {
                        $result = $row->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $schoolIds = $this->getDataLimitSchoolIds();
            if (is_array($schoolIds)) {
                $this->model->where($this->schoolLimitField, 'in', $schoolIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count = DeviceKey::where('device_id', $v->id)->where('status', DeviceKey::ACTIVATED)->count();
                    if ($count) {
                        $this->error('该激活码下有设备正在使用，不能删除');
                    }

                    DeviceKey::where('device_id', $v->id)->delete();
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}